﻿#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>

#include "productInfo.h"
#include "simpleLog.h"

#include "sellDataInfo.h"

std::string readFile(const std::string& filePath, std::vector<std::string>& header, std::vector<std::vector<std::string>>& data);

// 查找列名在标题行中的索引
int findIndex(const std::vector<std::string>& header, const std::string& columnName) {
  for (size_t i = 0; i < header.size(); ++i) {
    if (header[i] == columnName) {
      return static_cast<int>(i);
    }
  }
  return -1;
}

bool ProductInfo::ReadProductFile()
{
  std::vector<std::vector<std::string>> dataOri;
  auto readResult = readFile(file1Path, header, dataOri);
  if (!readResult.empty()) {
    logObj << "error:读取商品信息失败。文件名：" << file1Path << std::endl;
    return false;
  }
  int nameIndex = findIndex(header, ProductInfo::ProduceNameColName());
  if (nameIndex == -1) {
    logObj << "error:未找到列名: " << ProductInfo::ProduceNameColName() << std::endl;
    return false;
  }
  unitPriceIndex = findIndex(header, ProductInfo::UnitPriceColName());
  if (unitPriceIndex == -1) {
    logObj << "error:未找到列名: " << ProductInfo::UnitPriceColName() << std::endl;
    return false;
  }
  IDIndex = findIndex(header, ProductInfo::IDColName());
  if (IDIndex == -1) {
    logObj << "error:未找到列名: " << ProductInfo::IDColName() << std::endl;
    return false;
  }
  BarCodeIndex = findIndex(header, ProductInfo::BarCodeColName());
  if (BarCodeIndex == -1) {
    logObj << "error:未找到列名: " << ProductInfo::BarCodeColName() << std::endl;
    return false;
  }
  for (const auto& row : dataOri) {
    data[row[nameIndex]] = row;
  }
  logObj << "商品读取数据"<< data.size() << "条。" << std::endl;
  return true;
}

ProductInfo::ProductInfo(const std::string& file, Logger& log)
  :file1Path(file), logObj(log)
{
  readInfoSucc = ReadProductFile();
}

void ProductInfo::ParseSellData(const std::string& sellFile)
{
  if (!InitSucc()) {
    logObj << "需要先解析成功商品信息，再做操作，检查商品信息文件：" << file1Path << std::endl;
    return;
  }
  SellDataInfo sellInfoObj(sellFile, logObj);
  sellInfoObj.ParseToOutput(data, IDIndex, unitPriceIndex, BarCodeIndex);
}
